import 'package:casdon/modules/feedback/data/model/feedback_record_model.dart';
import 'package:casdon/modules/feedback/data/repository/feedback_repository.dart';

class FeedbackListUsecase {
  final FeedbackRepository _repository;

  const FeedbackListUsecase(this._repository);

  Future<List<FeedbackRecordModel>> execute() async {
    final list = await _repository.getFeedbackList();
    list.sort((a, b) {
      final orderDiff = _statusOrder(a.status) - _statusOrder(b.status);
      if (orderDiff != 0) {
        return orderDiff;
      }
      final timeDiff =
          _createdAtMillis(b.createTime) - _createdAtMillis(a.createTime);
      return timeDiff;
    });
    return list;
  }

  int _statusOrder(String? status) {
    const orderMapping = {'0': 0, '1': 1, '2': 2};
    final trimmed = status?.trim();
    return orderMapping[trimmed] ?? 3;
  }

  int _createdAtMillis(String? time) {
    if (time == null || time.isEmpty) {
      return 0;
    }
    final parsed = DateTime.tryParse(time);
    if (parsed != null) {
      return parsed.millisecondsSinceEpoch;
    }
    final intValue = int.tryParse(time);
    return intValue ?? 0;
  }
}
